# +----------------------------------------------------------------------
# | ChatWork智能聊天办公系统
# +----------------------------------------------------------------------
# | 软件声明: 本系统并非自由软件,未经授权任何形式的商业使用均属非法。
# | 版权保护: 任何企业和个人不允许对程序代码以任何形式任何目的复制/分发。
# | 授权要求: 如有商业使用需求,请务必先与版权所有者取得联系并获得正式授权。
# +----------------------------------------------------------------------
# | Author: ChatWork Team <2474369941@qq.com>
# +----------------------------------------------------------------------
import os
import importlib
from fastapi import FastAPI
from contextlib import asynccontextmanager

__all__ = ["configure_event"]


async def __dynamic_events(app: FastAPI, event: str):
    """ Dynamic execution events """
    root_path: str = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + os.sep
    if os.path.exists(root_path + "events.py"):
        module = importlib.import_module("events")
        clz = getattr(module, "AppEvents", None)
        if clz:
            function = getattr(clz, event, None)
            if function:
                await function(app)


@asynccontextmanager
async def configure_event(app: FastAPI):
    """ Configure events lifespan """
    # startup
    await __dynamic_events(app, "startup")
    yield
    # shutdown
    await __dynamic_events(app, "shutdown")
